<template>
  <div class="p-6">
    <el-card>
      <template #header>
        <div class="flex justify-between items-center">
          <span class="text-lg font-bold">招募管理</span>
          <el-button type="primary" @click="handleAdd">发布招募</el-button>
        </div>
      </template>

      <!-- 表格 -->
      <el-table :data="tableData" stripe border v-loading="loading">
        <el-table-column prop="id" label="编号" width="80" />
        <el-table-column prop="title" label="招募标题" />
        <el-table-column prop="descr" label="描述" show-overflow-tooltip />
        <el-table-column prop="requirements" label="要求" show-overflow-tooltip />
        <el-table-column prop="startDate" label="开始时间" />
        <el-table-column prop="endDate" label="结束时间" />
        <el-table-column label="操作" width="280">
          <template #default="scope">
            <el-button type="primary" link @click="handleEdit(scope.row)">编辑</el-button>
            <el-button type="success" link @click="handleViewApplications(scope.row)">查看申请</el-button>
            <el-button type="danger" link @click="handleDelete(scope.row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 新增/编辑弹窗 -->
    <el-dialog
      v-model="dialogVisible"
      :title="form.id ? '编辑招募' : '发布招募'"
      width="500px"
    >
      <el-form :model="form" label-width="100px" :rules="rules" ref="formRef">
        <el-form-item label="招募标题" prop="title">
          <el-input v-model="form.title" placeholder="请输入招募标题" />
        </el-form-item>
        <el-form-item label="描述" prop="descr">
          <el-input
            v-model="form.descr"
            type="textarea"
            :rows="3"
            placeholder="请输入招募描述"
          />
        </el-form-item>
        <el-form-item label="要求" prop="requirements">
          <el-input
            v-model="form.requirements"
            type="textarea"
            :rows="3"
            placeholder="请输入招募要求"
          />
        </el-form-item>
        <el-form-item label="开始时间" prop="startDate">
          <el-date-picker
            v-model="form.startDate"
            type="date"
            placeholder="选择开始时间"
            style="width: 100%"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item label="结束时间" prop="endDate">
          <el-date-picker
            v-model="form.endDate"
            type="date"
            placeholder="选择结束时间"
            style="width: 100%"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="save">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 申请列表弹窗 -->
    <el-dialog
      v-model="applicationDialogVisible"
      title="招募申请列表"
      width="800px"
    >
      <el-table :data="applicationList" stripe border v-loading="applicationLoading">
        <el-table-column prop="id" label="申请编号" width="80" />
        <el-table-column prop="studentName" label="学生姓名" width="100" />
        <el-table-column prop="clubName" label="申请社团" width="120" />
        <el-table-column prop="applicationTime" label="申请时间" />
        <el-table-column prop="status" label="状态">
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row.status)">
              {{ scope.row.status }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200">
          <template #default="scope">
            <el-button 
              v-if="scope.row.status === '待审核'"
              type="success" 
              link 
              @click="handleApprove(scope.row)"
            >
              通过
            </el-button>
            <el-button 
              v-if="scope.row.status === '待审核'"
              type="danger" 
              link 
              @click="handleReject(scope.row)"
            >
              拒绝
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import request from '@/utils/request'
import { ElMessage, ElMessageBox } from 'element-plus'

// 获取当前用户信息
const user = JSON.parse(localStorage.getItem('xm-pro-user')) || {}
const clubId = ref(null)
const tableData = ref([])
const loading = ref(false)
const dialogVisible = ref(false)
const formRef = ref(null)

// 申请列表相关
const applicationDialogVisible = ref(false)
const applicationList = ref([])
const applicationLoading = ref(false)
const currentRecruitment = ref(null)

// 表单数据
const form = reactive({
  id: null,
  clubId: null,
  title: '',
  descr: '',
  requirements: '',
  startDate: '',
  endDate: ''
})

// 表单验证规则
const rules = {
  title: [{ required: true, message: '请输入招募标题', trigger: 'blur' }],
  descr: [{ required: true, message: '请输入招募描述', trigger: 'blur' }],
  requirements: [{ required: true, message: '请输入招募要求', trigger: 'blur' }],
  startDate: [{ required: true, message: '请选择开始时间', trigger: 'change' }],
  endDate: [
    { required: true, message: '请选择结束时间', trigger: 'change' },
    {
      validator: (rule, value, callback) => {
        if (!value) {
          // 如果结束时间为空，交给required规则处理
          callback();
        } else if (form.startDate && new Date(value) < new Date(form.startDate)) {
          callback(new Error('结束时间不能早于开始时间'));
        } else {
          callback();
        }
      },
      trigger: 'change'
    }
  ]
}

// 加载招募列表
const loadRecruitments = async () => {
  loading.value = true
  try {
    const res = await request.get('/recruitment/selectAll', {
      params: {
        clubId: user.clubId
      }
    })
    if (res.code === '200') {
      // 格式化日期
      tableData.value = (res.data || []).map(item => ({
        ...item,
        startDate: item.startDate ? item.startDate.split(' ')[0].replace(/-/g, '.') : '',
        endDate: item.endDate ? item.endDate.split(' ')[0].replace(/-/g, '.') : ''
      }))
      if (tableData.value.length === 0) {
        ElMessage.info('暂无招募信息')
      }
    } else {
      ElMessage.error(res.msg || '获取招募信息失败')
    }
  } catch (err) {
    console.error('获取招募信息失败:', err)
    ElMessage.error('获取招募信息失败')
  } finally {
    loading.value = false
  }
}

// 新增按钮点击
const handleAdd = () => {
  Object.assign(form, {
    id: null,
    clubId: user.clubId,
    title: '',
    descr: '',
    requirements: '',
    startDate: '',
    endDate: ''
  })
  dialogVisible.value = true
}

// 编辑按钮点击
const handleEdit = (row) => {
  Object.assign(form, row)
  dialogVisible.value = true
}

// 删除按钮点击
const handleDelete = (id) => {
  ElMessageBox.confirm('确定要删除这条招募信息吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      const res = await request.delete(`/recruitment/delete/${id}`)
      if (res.code === '200') {
        ElMessage.success('删除成功')
        loadRecruitments()
      } else {
        ElMessage.error(res.msg || '删除失败')
      }
    } catch (err) {
      ElMessage.error('删除失败')
    }
  })
}

// 保存表单
const save = async () => {
  if (!formRef.value) return
  await formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        const url = form.id ? '/recruitment/update' : '/recruitment/add'
        const res = await request.post(url, form)
        if (res.code === '200') {
          ElMessage.success(form.id ? '修改成功' : '发布成功')
          dialogVisible.value = false
          loadRecruitments()
        } else {
          ElMessage.error(res.msg || (form.id ? '修改失败' : '发布失败'))
        }
      } catch (err) {
        ElMessage.error(form.id ? '修改失败' : '发布失败')
      }
    }
  })
}

// 查看申请列表
const handleViewApplications = async (row) => {
  currentRecruitment.value = row
  applicationDialogVisible.value = true
  await loadApplications(row.id)
}

// 加载申请列表
const loadApplications = async (recruitmentId) => {
  applicationLoading.value = true
  try {
    const res = await request.get('/recruitmentapplication/selectByRecruitmentId', {
      params: {
        recruitmentId: recruitmentId
      }
    })
    if (res.code === '200') {
      applicationList.value = res.data || []
    } else {
      ElMessage.error(res.msg || '获取申请列表失败')
    }
  } catch (err) {
    console.error('获取申请列表失败:', err)
    ElMessage.error('获取申请列表失败')
  } finally {
    applicationLoading.value = false
  }
}

// 审批通过
const handleApprove = async (row) => {
  try {
    const res = await request.put('/recruitmentapplication/updateById', {
      ...row,
      status: '通过'
    })
    if (res.code === '200') {
      ElMessage.success('已通过申请')
      loadApplications(currentRecruitment.value.id)
    } else {
      ElMessage.error(res.msg || '操作失败')
    }
  } catch (err) {
    ElMessage.error('操作失败')
  }
}

// 审批拒绝
const handleReject = async (row) => {
  try {
    const res = await request.put('/recruitmentapplication/updateById', {
      ...row,
      status: '不通过'
    })
    if (res.code === '200') {
      ElMessage.success('已拒绝申请')
      loadApplications(currentRecruitment.value.id)
    } else {
      ElMessage.error(res.msg || '操作失败')
    }
  } catch (err) {
    ElMessage.error('操作失败')
  }
}

// 获取状态类型
const getStatusType = (status) => {
  switch (status) {
    case '待审核':
      return 'warning'
    case '通过':
      return 'success'
    case '不通过':
      return 'danger'
    default:
      return 'info'
  }
}

// 获取状态文本
const getStatusText = (status) => {
  switch (status) {
    case 'pending':
      return '待审核'
    case 'approved':
      return '已通过'
    case 'rejected':
      return '已拒绝'
    default:
      return '未知'
  }
}

// 页面加载时获取社团ID
onMounted(() => {
  loadRecruitments();
})
</script>

<style scoped>
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style> 